//
// Created by Administrator on 2019/12/10.
//

#include "include/PThreadLearn.h"


int PThreadLearn::ThreadCount = 5;
int PThreadLearn::threadSharedV = 5;

pthread_mutex_t PThreadLearn::mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t PThreadLearn::condition = PTHREAD_COND_INITIALIZER;

PThreadLearn::PThreadLearn() {
    status = new pthread_t[5];

    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&condition, NULL);
}

PThreadLearn::~PThreadLearn() {
    delete[] status;
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&condition);
}

void PThreadLearn::start5Thread() {
    //设置线程属性：定义，初始化，设置，销毁
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    for (int i = 0; i < ThreadCount; ++i) {
        int ret = pthread_create(&this->status[i], &attr, runner, (void*)nullptr);
        if(ret)
            cout<<"create thread failed"<<endl;
    }
    pthread_attr_destroy(&attr);
}

void *PThreadLearn::runner(void *arg) {
    pthread_mutex_lock(&mutex);
    PThreadLearn::threadSharedV--;
    cout << "the global value = "<<PThreadLearn::threadSharedV<<endl;
//    pthread_cond_signal(&condition);
    pthread_mutex_unlock(&mutex);
    return nullptr;
}

